﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mojito.Data.Initialization;
using Mojito.WebSite;
using Sohobloo.SoCommon.Log;

namespace UT_WebAPI
{
    [TestClass]
    class TestUtility
    {
        private static HttpServer Server { get; set; }
        public static HttpMessageInvoker Client { get; private set; }

        [AssemblyInitialize]
        public static void TestAssemblyInitialized(TestContext testContext)
        {
            var config = new HttpConfiguration();
            
            config.DependencyResolver = MefUtConfig.RegisterSolver();

            WebApiConfig.Register(config);

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            LogInitializer.Initialize();
            DbInitializer.Initialize(DbInitializer.DbInitializMode.DropCreate);

            Server = new HttpServer(config);
            Client = new HttpMessageInvoker(TestUtility.Server);
        }

        [AssemblyCleanup]
        public static void TestAssemblyCleanup()
        {
            Server.Dispose();
            Client.Dispose();
        }

        public static HttpRequestMessage CreatRequest(HttpMethod method, string url)
        {
            var request = new HttpRequestMessage(method, url);
            request.Headers.Clear();
            request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));

            return request;
        }

        public static HttpResponseMessage SendAsync(HttpMethod method, string url)
        {
            HttpResponseMessage response;
            using (var request = TestUtility.CreatRequest(HttpMethod.Post, url))
            {
                //var client = new HttpMessageInvoker(TestUtility.Server);
                var client = new HttpClient(Server);
                response = client.SendAsync(request, CancellationToken.None).Result;
            }
            return response;
        }
    }
}
